package com.spark.gaea.data.mybatis.backend;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.spark.gaea.data.mybatis.DataPermissionsBacked;
import com.spark.gaea.utils.HttpUtil;
import com.spark.gaea.utils.exception.GaeaRuntimeException;
import com.spark.gaea.utils.json.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class HttpDataPermission implements DataPermissionsBacked {
	@Autowired
	Environment env;
	private HttpUtil http;
	private ObjectMapper mapper;
	private String mdmApiUrl;

	public HttpDataPermission() {
		this.http = new HttpUtil();
		this.mapper = JsonUtil.getMapper();
	}

	@PostConstruct
	public void init() {
		this.mdmApiUrl = HttpUtil.getAppUrl(this.env.getProperty("mdm_url")) + "api/";
	}

	@Override
	public Set<Map<String, String>> getSqlParameterList(final String userId, final String sqlId) {
		final Map<String, String> params = Maps.newHashMap();
		params.put("userId", userId);
		params.put("sqlId", sqlId);
		params.put("command", "getSqlParameter");
		try {
			System.out.println(this.mdmApiUrl + "sqlPar" + "/" + "getSqlParameter");
			final String response = this.http.post(this.mdmApiUrl + "sqlPar" + "/" + "getSqlParameter", params);
			return (Set<Map<String, String>>) this.mapper.readValue(response, (Class) HashSet.class);
		} catch (IOException e) {
			throw new GaeaRuntimeException("远程连接无效", e);
		}
	}
}
